﻿/**
 * 送餐地址页面JS
 * 
 * @author: 刘晓杰
 * @date: 2013-3-7
 */

var KFC_POST = function(action, data, callback){
    $.ajax({
        url : requestContextPath + "/" + action,
        data : data,
        type : 'post',
        dataType : 'json',
        beforeSend : function(){
        	
        },
        success : function(o){

            // 可添加预处理

            if(callback && $.isFunction(callback)){
                callback(o);
            }
        },
        complete: function(XMLHttpRequest, textStatus){
			
		},
        error : function(){
            base.yumAlert(property.BadRequest);
        }
    });
};


// --------------------------------  基本信息  begin  ------------------------------------------------ //
var KFC_Base = function(me){
    var emailEl = $('#userEmail');
    var usernameEl = $('#username');
    var modifyInfo = $('.modifyBtn');

    //-- 设置默认提示语
    usernameEl.tip(property.customerNameTip);
    
    //-- 验证邮箱是否被注册
    emailEl.blur(function(){
    	/** 非法字符验证 */
    	if (common.isStr2(emailEl.val(), 1)) {
    		base.yumAlert(property.invaildStringError);
    		emailEl.val('');
        	return;
    	}
        if (emailEl.val() != '' && common.isEmail(emailEl.val())){
            KFC_POST(
                '/checkUser.action',
                { email : emailEl.val() },
                function(o){
                    if(o.code == serviceCode.CUSTOMER_NOT_FOUND){
                        return;
                    }else if(o.code == serviceCode.SUC_CODE){
                        base.yumConfirm(
                            property.emailExist,
                            function(){
                                base.setAction('customer.action');
                            },
                            function(){
                            	emailEl.val('');
                            }
                        );
                    }else if(o.code == serviceCode.NEED_PASSWORD){
                    	base.yumConfirm(
                            property.emailExist2,
                            function(){
                            	base.setAction('customer.action');
                            },
                            function(){
                            	emailEl.val('');
                            }
                        );
                    }
                }
            );
        }
    });
    
    var tempVal = '';
    usernameEl.change(function(){
    	var val = this.value;
    	var length = val.replace(/[^\x00-\xff]/g, 'xx').length;
    	if(length > 24){
    		base.yumAlert(property.notLonger);
    		this.value = tempVal;
    		return;
    	}
        if (!common.isStr(val)){
        	base.yumAlert(property.customerNameNotRight);
        	this.value = tempVal;
        	return;
        }
    	tempVal = val;
    });

    var validateInfo = function() {
        var email = $.trim(emailEl.val());
        var name = $.trim(usernameEl.val());
        var gender = $('input[name=gender]:checked');

        if(!me.isNewUser){
            return true;
        }

        if (emailEl[0] && emailEl.is(':visible')) {
            if (email == '') {
                base.yumAlert(property.emailNotNull);
                return false;
            }
            if (!common.isEmail(email)) {
                base.yumAlert(property.emailNotcorrect);
                return false;
            }
        }

        if (usernameEl[0] && usernameEl.is(':visible')) {
            if (name == '' || name == property.customerNameTip) {
                base.yumAlert(property.customerNameNotNull);
                return false;
            }
            
            if (common.isStr2(name,2)){
            	base.yumAlert(property.customerNameNotRight);
				 return false;
            }

            if (!gender[0]) {
                base.yumAlert(property.genderNotChoose);
                return false;
            }
        }
        return true;
    };


    //--  修改、保存用户基本信息（姓名、性别）
    var modify = function(){
        var _this = $(this);
        var usernameValue = usernameEl.val() == property.customerNameTip ? '' : usernameEl.val();
        var gender = $('input[name=gender]:checked');
        var customrNameEl = $('.customerName');
        var tab = function() {
        	usernameEl.val(property.customerNameTip);
        	if(gender[0])gender[0].checked = false;
            _this.parent().hide().siblings().show();
        };
        var genderVal = gender.val();

        if (usernameEl.is(':visible')) {
            if (usernameValue == '') {
                base.yumAlert(property.customerNameNotNull);
                return;
            }
            
            if (common.isStr2(usernameValue,2)){
            	 base.yumAlert(property.customerNameNotRight);
				 return false;
            }
            
            // 判断姓名是否为特殊字符
//            var arr = new Array("<script>","script"," src","select ",
//            					"update","delete","insert ","<",">"," style",
//            					"%","&",":","|","'","/","\"","!",
//            					"％","”","“","﹛","﹚","﹙","﹜","＋","[","]","！","@","?",
//            					"#","%","……","*","（","）","{","}","《","》","？","，","。",
//            					"$","(",")");
//            for(var i=0;i<arr.length;i++){
//				 if(usernameValue.indexOf(arr[i])>=0){
//					 base.yumAlert(property.customerNameNotRight);
//					 return false;
//				 }
//			 } 
            
            if (!genderVal) {
                base.yumAlert(property.genderNotChoose);
                return;
            }
            KFC_POST(
                '/updateInfo.action',
                {
                    customerName : $.trim(usernameValue),
                    gender : gender.val()
                },
                function(o) {
                    if (o.code == serviceCode.SUC_CODE){
                        genderVal = genderVal == 0 ? pageMessage.common_Mr : pageMessage.common_Ms;
                        var El = _this.parent().siblings().children();
                        _this.parent().siblings().text( usernameValue + ' ' + genderVal).append(El);
                        customrNameEl.text($.trim(usernameValue + ' ' + genderVal));
                        tab();
                    } else{
                    	base.yumAlert(property.serviceUnknown);
                    }
                }
            );
        } else {
            tab();
        }
    };

    this.isFinish = function(){
        return validateInfo();
    };
    
    modifyInfo.live('click', modify);
};
// --------------------------------  基本信息  end  ------------------------------------------------ //



// --------------------------------  联系方式  begin  ------------------------------------------------ //
var KFC_Phone = function(me){
    var addPhone = $('#addPhone');
    var phone_1 = $('#phone_1');
    var addPhoneBtn = $('#addPhoneBtn');
    var savePhoneBtn = $('#savePhoneBtn');
    var selectPhoneRadio = $('input[name=selPhoneId]');
    var deleteBtn = $('.deletePhoneBtn');
    var newMobile = $('#newMobile');    // 手机号
    var newTel1 = $('#newTel1');        // 区号
    var newTel2 = $('#newTel2');        // 电话号
    var newTel3 = $('#newTel3');        // 分机号

    var phoneTemp = '<tr><td>{0}</td><td>{1}</td><td align="center">'
        + '<input name="phone" type="hidden" value="{1}">'
        + '<input name="selPhoneId" type="radio" value="{2}">'
        + '</td><td align="center"><div class="del_btn" value="{2}"><a href="javascript:;" class="deletePhoneBtn"><img src="res/images/delete_icon_2.gif"></a></div></td></tr>';

    var phoneList = $('#telephone_1 .info_table_1');
    var selectItem = $('<div class="selectItem"><div class="selectItemCount"></div></div>');

    // 设置默认提示语
    newMobile.tip(property.mobileTip);
    newTel1.tip(property.areaCodeTip);
    newTel2.tip(property.telephoneTip);
    
    //-- 重置输入框
    var reset = function(){
        newMobile.val(property.mobileTip);
        newTel1.val(property.areaCodeTip);
        newTel2.val(property.telephoneTip);
        newTel3.val('');
    };

    //-- 选择按钮点击事件
    selectPhoneRadio.live('click', function(){
        //-- 重置输入框
        reset();
        addPhone.hide();
        addPhoneBtn.show();
        savePhoneBtn.hide();
    });
    
    //-- 把页面上的联系号码添加至JS对象中，以便判断数量
    selectPhoneRadio.each(function(){
    	var $this = $(this);
    	me.phoneList.push($this.next('[name=phone]').val());
    });

    selectPhoneRadio.live('click', function(){
        $(this).click(function(){
            //-- 重置输入框
            reset();
        });
    });
    
    addPhoneBtn.click(function(){
        $(this).hide();
        savePhoneBtn.show();
        addPhone.show();
        $('input[name=selPhoneId]').each(function(){
        	this.checked = false;
        });
    });
    
    //-- 自动获取区号
    newTel1.keyup(function(e){
    	var $this = $(this);
    	var cityName = $.trim(this.value);
    	
    	if (cityName && (!common.isStr(cityName) || common.isStr2(cityName, 1))) {
    		selectItem.remove();
    		base.yumAlert(property.invaildStringError);
        	return;
    	}
    	if((e.keyCode > 65 && e.keyCode < 90) || e.keyCode == 32 || e.keyCode == 8){
//    		var $this = $(this);
//        	var cityName = $.trim(this.value);
        	if(cityName && cityName != property.areaCodeTip){
        		if(/^\d+$/.test(cityName)){
            		selectItem.remove();
            		return;
            	}
            	
            	selectItem.find('.selectItemCount').html('<img src="res/images/loading.gif"/>');
            	selectItem.css({ top : '50px', left : '40px' });
            	$(this).after(selectItem.show());
            	
            	var selectFunction = function(args){
            		return function(){;
                    	$this.val(args.zoneno);
                    	selectItem.remove();
                    };
            	};
            	
            	KFC_POST(
            			'/queryCity.action',
            			{cityName : cityName},
            			function(o){
            				var ul = $('<ul></ul>');
                            if (o && o.length > 0) {
                                for ( var k in o) {
                                    var args = o[k];
                                    var li = $('<li>' + args.name + args.districtName + '-' + args.zoneno + ' ' + args.nameen + '</li>');
                                    li.hover(function() {
                                        $(this).addClass('hover');
                                    }, function() {
                                        $(this).removeClass('hover');
                                    });
                                    li.click(selectFunction(args));
                                    ul.append(li);
                                }
                            } else {
                                ul.append('<li>'+property.noMatch+'</li>');
                            }
                            selectItem.find('.selectItemCount').html('').append(ul);
            			});
        	}else{
        		selectItem.remove();
        	}
    	}
    });
    

    var save = function(){
        var newMobileVal = $.trim(newMobile.val());
        var newTel1Val = $.trim(newTel1.val());
        var newTel2Val = $.trim(newTel2.val());
        var newTel3Val = $.trim(newTel3.val());
        var index = $('input[name=selPhoneId]').size();

        if (newMobileVal == property.mobileTip) {
            newMobileVal = '';
        }
        if (newTel1Val == property.areaCodeTip) {
            newTel1Val = '';
        }
        if (newTel2Val == property.telephoneTip) {
            newTel2Val = '';
        } 
        if (!newMobileVal && !newTel1Val && !newTel2Val) {
            base.yumAlert(property.mobiTelephone);
            return;
        }

        if (newMobileVal) {
            if (common.isMobile(newMobileVal)) {
                //--
            } else {
                base.yumAlert(property.mobNotcorrect);
                return;
            }
        }

        if ( newTel1Val ) {
            if (!common.isAreaCode(newTel1Val)) {
                base.yumAlert(property.areaCodeNotCorrent);
                return;
            }
            if( !newTel2Val ){
            	base.yumAlert(property.teleNotCorrent);
                return;
            }
        }

        if ( newTel2Val ) {
            if (!common.isTelephone(newTel2Val)) {
                base.yumAlert(property.teleNotCorrent);
                return;
            }
            if( !newTel1Val){
            	base.yumAlert(property.areaCodeNotCorrent);
                return;
            }
        }
        
        if(newTel3Val){
        	if(!/^\d+$/.test(newTel3Val)){
        		base.yumAlert(property.extensionNumNotCorrent);
        		return;
        	}
        }
        
        if(me.phoneList.length >= 10){
        	base.yumAlert(property.overTenPhone);
        	return;
        }
        
        // ---  用户为登录用户
        if ( !me.isNewUser ){
            var telePhone = newTel1Val + newTel2Val;
            if (telePhone != '' && newTel3Val != '') {
                telePhone += '-' + newTel3Val;
            }

            KFC_POST(
                '/addPhones.action',
                { phone1 : newMobileVal, phone2 : telePhone },
                function(o){
                    if (o.code == serviceCode.SUC_CODE) {
                        var phoneFlag = o.message.indexOf(",");
                        if (phoneFlag != -1) {
                            var phoneId1 = o.message.substring(0, phoneFlag);
                            var phoneId2 = o.message.substring(phoneFlag + 1);
                            phoneList.append(phoneTemp.format([ property.mobile, newMobileVal, phoneId1 ]));
                            phoneList.append(phoneTemp.format([ property.fixedPhone, telePhone, phoneId2 ]));
                            me.phoneList.push(newMobileVal);
                            me.phoneList.push(telePhone);
                        } else {
                        	if(newMobileVal){
                        		phoneList.append(phoneTemp.format([ property.mobile, newMobileVal, o.message ]));
                        		me.phoneList.push(newMobileVal);
                        	}else{
                        		phoneList.append(phoneTemp.format([ property.fixedPhone, telePhone, o.message ]));
                        		me.phoneList.push(telePhone);
                        	}
                        }
                        
                        addPhoneBtn.show();
                        addPhone.hide();
                        if(!phone_1.is(':visible'))phone_1.removeClass('dn');
                        base.yumAlert(property.saveSuccessfully);
                    } else if(o.code == '113'){
                    	base.yumAlert(property.mobileExitCantAdd);
                    } else{
                    	base.yumAlert(property.saveFailed);
                    }
                }
            );
        }else{
            if(newMobileVal){
            	if($.inArray(newMobileVal, me.phoneList) !== -1){
            		base.yumAlert(property.mobileExitCantAdd);
            		return;
            	}
                phoneList.append(phoneTemp.format([ property.mobile, newMobileVal, index++ ]));
                me.phoneList.push(newMobileVal);
            }
            if(newTel2Val){
                var newTel = newTel1Val + newTel2Val;
                if(newTel3Val){
                    newTel += '-' + newTel3Val;
                }
                if($.inArray(newTel, me.phoneList) !== -1){
            		base.yumAlert(property.mobileExitCantAdd);
            		return;
            	}
                phoneList.append(phoneTemp.format([ property.fixedPhone, newTel, index++ ]));
                me.phoneList.push(newTel);
            }
        	
            addPhoneBtn.show();
            addPhone.hide();
            if(!phone_1.is(':visible'))phone_1.removeClass('dn');
            base.yumAlert(property.saveSuccessfully);
        }
        
        //-- 重置输入框
        reset();
        //  addPhoneBtn.show();
    };

    //--  删除电话
    var del = function(){
        var element = $(this);
        var deleteflag = element.parent().attr('deleteflag');
        var phoneId = element.parent().attr('value');

        if (deleteflag == 1) {
            base.yumAlert(property.phoneCantDelete);
            return;
        }
        base.yumConfirm(
        		property.deletePhoneWarn, 
        		function(){
		        	if(me.isNewUser){
		                element.closest('tr').remove();
		                me.phoneList.pop();
		            }else{
		            	KFC_POST(
		                        '/delPhone.action',
		                        {phoneId : phoneId},
		                        function(o) {
		                            if (o.code == serviceCode.SUC_CODE) {
		                                element.closest('tr').remove();
		                                me.phoneList.pop();
		                                base.yumAlert(property.deleteSuccessfully);
		                            } else if (o.code == serviceCode.UNKNOWN_SERVICE_ERROR) {
		                                base.yumAlert(property.serviceUnknown);
		                            }else{
		                            	base.yumAlert(property.deleteFailed);
		                            }
		                        }
		                    );
		            }
        });
        
    };

    this.isFinish = function(){
    	if(savePhoneBtn.is(':visible')){
    		savePhoneBtn.click();
    		return false;
    	}
    	//如果只有一个联系方式，则选中
    	if(me.phoneList.length == 1) {
    		$('input[name=selPhoneId]').each(function(){
            	this.checked = true;
            });
    	}
    	if(!$('[name=selPhoneId]:checked')[0]){
    		base.yumAlert(property.phoneNotSelected);
    		return false;
    	}
        return true;
    };
    
    
    savePhoneBtn.click(save);
    deleteBtn.live('click', del);
};
// --------------------------------  联系方式  end  ------------------------------------------------ //



// --------------------------------  地址  begin  ------------------------------------------------ //
var KFC_Address = function(me){
    var cityName = $('#cityName');
    var address2 = $('#address2');
    var address3 = $('#address3');
    var addAddress = $('#addAddress');
    var addressList = $('#address_1');
    var delivery = $('#delivery');
    var selectBtn = address2.next('img');
    var addAddressBtn = $('#addAddressBtn');
    var saveAddressBtn = $('#saveAddressBtn');
    var deleteBtn = $('.deleteAddressBtn');
    var addressRadio = $('input[name=selAddressId]');
    var selectCity = {};
    var selectAddress = {};
    
    var selectItem = $('<div class="selectItem"><div class="selectItemCount"></div></div>');
    var addressTemp = '<tr><td>{0}</td><td>{3} {4}</td><td align="center">'
        + '<input name="selAddressId" type="radio" value="{6}">'
        + '<input name="nCityCode" type="hidden" value="{1}">'
        + '<input name="nMainaddressId" type="hidden" value="{2}">'
        + '<input name="nMainaddress" type="hidden" value="{3}">'
        + '<input name="nSupplementaladdress" type="hidden" value="{4}">'
        + '<input name="nStoreId" type="hidden" value="{5}">'
        + '</td><td align="center"><a href="javascript:;" class="deleteAddressBtn" tip="{2}"><img src="res/images/delete_icon_2.gif"></a></td></tr>';

    var deliveryTimeTemp = '<tr tip="deliveryTime"><td colspan="4"><div class="select_time" style="margin-top: -10px;position:relative;">' +
        '<div class="select_time_span1">'+
        property.deliveryTime+
        '</div>' +
        '<div><p><input name="sendfoodtime" type="radio" checked="checked" tip="inTime" style="vertical-align:middle;margin:-4px 0 0;" /> <span>'+
        property.afterSubmit+
        '</span><span class="bc">{0}</span>'+
        property.timeArrive+
        '</p>' +
        '<div style="position:relative;"><div class="fl_l"><input {2} class="sendfoodtime-style" name="sendfoodtime" type="radio" value="{1}" /> <span>'+
        property.currentLater+
        '</span></div>' +
        '<div class="selectTime"></div>' +
        '</div></div></div></td></tr>';
    
    var openOnlinePay = '<input name="supportonlinepay" type="hidden" value="{0}"/>';
    

    //-- 下拉框选择事件
    var selectFunction = function() {
        var args = arguments[0];
        var element = args.element;
        var value = args.value;
        var data = args.data;
        var districtName = args.districtName;

        return function() {
        	if(districtName){
        		value+=districtName;
        	}
            element.val(value);
            selectItem.remove();
            element == cityName ? selectCity = data : selectAddress = data;
        };
    };
    
    //-- 清空输入框
    var reset = function(){
    	cityName.val(property.cityTip);
        address2.val(property.mainAddressTip);
        address3.val(property.suppleMentalAddressTip);
    };

    //-- 设置默认提示语
    cityName.tip(property.cityTip);
    address2.tip(property.mainAddressTip);
    address3.tip(property.suppleMentalAddressTip);

    //-- 把页面上的地址ID添加至JS对象中，以便判断数量
    addressRadio.each(function(){
    	me.addressList.push(this.value);
    });
    //-- 查询城市
    cityName.keyup(function(e) {
    	var cityNameVal = $.trim(this.value);
		cityNameVal = cityNameVal.replace(/[^\a-zA-Z\u4E00-\u9FA5]/g,'');//过滤非字母和非汉字的字符
    	
    	if (cityNameVal && (!common.isStr(cityNameVal) || common.isStr2(cityNameVal, 1))) {
    		selectItem.remove();
    		base.yumAlert(property.invaildStringError);
        	return;
    	}
    	if((e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode == 32 || e.keyCode == 8){
    	
//    		var cityNameVal = $.trim(this.value);
//    		cityNameVal = cityNameVal.replace(/[^\a-zA-Z\u4E00-\u9FA5]/g,'');//过滤非字母和非汉字的字符
            selectItem.css({ top : '33px', left : '86px' });
            if (cityNameVal && cityNameVal != property.cityTip){
                selectItem.find('.selectItemCount').html('<img src="res/images/loading.gif"/>');
                $(this).after(selectItem.show());
                KFC_POST(
                    '/queryCity.action',
                    {cityName : cityNameVal},
                    function(o) {
                        var ul = $('<ul></ul>');
                        if (o && o.length > 0) {
                            for ( var k in o) {
                                var args = o[k];
                                var li = $('<li>' + args.name + args.districtName + args.nameen + '</li>');
                                li.hover(function() {
                                    $(this).addClass('hover');
                                }, function() {
                                    $(this).removeClass('hover');
                                });
                                li.click(selectFunction({
                                    element : cityName,
                                    value : args.name,
                                    districtName:args.districtName,
                                    data : args
                                }));
                                ul.append(li);
                            }
                        } else {
                            ul.append('<li>'+property.noMatch+'</li>');
                        }
                        selectItem.find('.selectItemCount').html('').append(ul);
                    }
                );
            } else {
                selectItem.remove();
                selectCity = {};
            }
    	}
    });
    
    cityName.change(function(){
    	if(!this.value){
    		selectCity = {};
    	}
    	selectAddress= {};
    	address2.val(property.mainAddressTip);
    });

    //-- 搜索城区
    selectBtn.click(function(){
        var address2Val = $.trim(address2.val());
       
        // 判断城市是否已选
        if (!selectCity.hasOwnProperty('citycode')) {
            base.yumAlert(property.pleaseChooseCityFirst);
            return;
        }
        if ('' == address2Val || address2Val == property.mainAddressTip) {
            base.yumAlert(property.communityDescNotNull);
            return;
        }
        if (common.isStr2(address2Val, 3)) {
        	selectItem.remove();
    		base.yumAlert(property.invaildStringError);
        	return;
    	}
        
        selectItem.css({left : '268px'});
        selectItem.find('.selectItemCount').html('<img src="res/images/loading.gif">');
        address2.after(selectItem.show());
        KFC_POST(
            '/searchAddressList.action',
            {cityCode : selectCity.citycode, streetName : address2Val},
            function(o) {
                var ul = $('<ul></ul>');
                if (o && o.length > 0) {
                    for ( var k in o) {
                        var args = o[k];
                        var li = $('<li>' + args.streetName + '</li>');
                        li.hover(function() {
                            $(this).addClass('hover');
                        }, function() {
                            $(this).removeClass('hover');
                        });
                        li.click(selectFunction({
                            element : address2,
                            value : args.streetName,
                            data : args
                        }));
                        ul.append(li);
                    }
                } else {
                    ul.append('<li>'+property.noMatch+'</li>');
                }
                selectItem.find('.selectItemCount').html('').append(ul);
            }
        );
    });
    
    address2.focus(function() {
//        selectItem.remove();
    });
    
    address2.change(function(){
    	selectAddress = {};
    	selectBtn.click();
    });

    //-- 添加地址
    var add = function(){
    	reset();
        $(this).hide();
        addAddress.show();
        $('input[name=selAddressId]').each(function(){
        	this.checked = false;
        	$(this).closest('table').find('.td_no_border').removeClass('td_no_border').next('[tip=deliveryTime]').remove();
        });
    };

    //-- 保存地址
    var save = function(){
    	if(me.addressList.length >= 10){
    		base.yumAlert(property.overTenAddress);
    		return;
    	}
    	if(!selectCity.hasOwnProperty('id')){
    		base.yumAlert(property.pleaseChooseCityFirst);
    		return;
    	}
    	if(!selectAddress.hasOwnProperty('id')){
    		base.yumAlert(property.pleaseChooseMainAddress);
    		return;
    	}
        var cityNameVal = $.trim(cityName.val());
        var address2Val = $.trim(address2.val());
        var address3Val = $.trim(address3.val());
        
        var check = /^(?=.*?[!@#$%^&*、<>《》,\\\/\[\]\'\;\=+！＃￥……]).*$/;
        var index = $('input[name=selAddressId]').size();
        var showEl = function(args){
        	var cityVal = selectCity.name;
        	if (selectCity.districtName){
        		cityVal+=selectCity.districtName;
        	}
        	addressList.find('table').append(
                    addressTemp.format([
                        cityVal,
                        selectCity.citycode,
                        selectAddress.streetId,
                        selectAddress.streetName, address3Val,
                        selectAddress.storeCode, args ]));
                addAddress.hide();
                addressList.show();
                addAddressBtn.show();
        };
        
        if ('' == cityNameVal || cityNameVal == property.cityTip) {
            base.yumAlert(property.cityNotNull);
            return false;
        }
        if ('' == address2Val || address2Val == property.mainAddressTip) {
            base.yumAlert(property.communityNotNull);
            return false;
        }
        if ('' == address3Val || address3Val == property.suppleMentalAddressTip) {
            base.yumAlert(property.suppleMentalAddressStart);
            return false;
        }
//        if(address3Val.length > 25){
//        	base.yumAlert(property.suppleMentalAddressTooLong);
//        	return false;
//        }
        if(check.test(address3Val)){
        	base.yumAlert(property.addressFalse);
        	return false;
        }
        if(/^(\d+)?(.+)?$/.exec(address3Val)[1] && /^(\d+)?(.+)?$/.exec(address3Val)[1].length > 4){
        	base.yumAlert(property.addressBlank);
        	return false;
        }
        var length = address3Val.replace(/[^\x00-\xff]/g, 'xx').length;
        if(length >= 60){
    		base.yumAlert(property.suppleMentalAddressTooLong);
    		return;
    	}
        
        /** 非法字符校验*/
        if (common.isStr2(address3Val, 1) || common.isStr2(address2Val, 1) || common.isStr2(cityNameVal, 1)) {
    		base.yumAlert(property.invaildStringError);
        	return false;
    	}

        if (!me.isNewUser) {
            KFC_POST(
                '/addAddress.action',
                {
                    cityId : selectCity.citycode,
                    mainAddressId : selectAddress.streetId,
                    mainAddress : address2Val,
                    supplementaladdress : address3Val,
                    newStoreId : selectAddress.storeCode
                },
                function(o) {
                    if (o.code == serviceCode.SUC_CODE){
                    // -- 该message字段存储了 新增的地址id 属于字段重用
                        showEl(o.message);
                        base.yumAlert(property.saveSuccessfully);
                        me.addressList.push(o.message);
                        
                    }
                    // -- 地址不在送餐范围之内	code : 10010
                    else if(o.code == serviceCode.OUT_OF_ADDR_DELIVERY){
                    	base.yumAlert(property.addressNotInDelivery);
                    }
                    // -- 地址已存在 
                    else if(o.code == '114'){
                        base.yumAlert(property.addressExitCantAdd);
                    } 
                    // --地址未找到
                    else if(o.code == '25'){
                    	base.yumAlert(codeMessage.error25);
                    }
                    else if (o.code == serviceCode.UNKNOWN_SERVICE_ERROR) {
                        base.yumAlert(property.serviceUnknown);
                    }
                }
            );
        }else{
        	for(var i in me.addressList){
        		if(me.addressList[i] == selectCity.citycode + selectAddress.streetId + address3Val){
        			base.yumAlert(property.addressExitCantAdd);
        			return;
        		}
        	}
        	KFC_POST(
        			'/addAddressNew.action',
        			{
        				cityCode : selectCity.citycode,
        				mainAddressId : selectAddress.streetId,
        				supplementaladdress : address3Val
        			},
        			function(o){
        				if(o.code == serviceCode.SUC_CODE){
        					showEl(index);
        					me.addressList.push(selectCity.citycode + selectAddress.streetId + address3Val);
        					base.yumAlert(property.saveSuccessfully);
        				}
        				// -- 地址不在送餐范围之内	code : 10010
                        else if(o.code == serviceCode.OUT_OF_ADDR_DELIVERY){
                        	base.yumAlert(property.addressNotInDelivery);
                        }
        				else if(o.code == '24'){
        					base.yumAlert(codeMessage.error24);
        				}
        				// --地址未找到
                        else if(o.code == '25'){
                        	base.yumAlert(codeMessage.error25);
                        }
        				// -- 地址已存在 
        				else if(o.code == '114'){
                            base.yumAlert(property.addressExitCantAdd);
                        }
	    				else if (o.code == serviceCode.UNKNOWN_SERVICE_ERROR) {
	                        base.yumAlert(property.serviceUnknown);
	                    }
        			}
        		);
        };
        
    };

    //-- 选择地址
    var selectRadio = function(){
    	addAddress.hide();
    	addAddressBtn.show();
    	selectItem.remove();
    	
        var $this = $(this);
        var deliverytime = $this.attr('deliverytime');
        $this.closest('table').find('.td_no_border').removeClass('td_no_border').next('[tip=deliveryTime]').remove();
        var parent = $this.parent();
        var supplementaladdress = parent.find('input[name=nSupplementaladdress]').val();
        var nCityCode = parent.find('input[name=nCityCode]').val();
        var nMainaddressId = parent.find('input[name=nMainaddressId]').val();
        var storeCode = parent.find('input[name=nStoreId]').val();
        
        var val = $this.val();
//        var flag = $this.attr('flag');
//        var storeClosedFlag = $this.attr('storeClosedFlag');
        if(me.isNewUser){
//            var houseNum = /^(\d+)(.+)?$/.exec(supplementaladdress);
//            houseNum = houseNum? houseNum[1] : 9999;
            //val = nCityCode + '-' + nMainaddressId + '-' + houseNum;
            val = nCityCode + '-' + nMainaddressId + '-' + supplementaladdress; 
        }
        
//        if(flag == '25'){
//            base.yumAlert(property.addressNotInDeliveryHelp);
//            this.checked = false;
//            return;
//        }
//        if (storeClosedFlag == '1'){
//        	base.yumAlert(property.storeClosed);
//        	this.checked = false;
//        	return;
//        }
        if(deliverytime && deliverytime != ''){
            var $deliveryTimeTemp = $(deliveryTimeTemp.format([deliverytime, val]));
            $this.closest('tr').after($deliveryTimeTemp).addClass('td_no_border');
            delivery.val(deliverytime);
            return;
        }
        //-- 动态获取送餐时间
        else{
        	KFC_POST(
                    '/getDeliveryTime.action',
                    {
                    	cityCode : nCityCode,
                    	mainAddressId : nMainaddressId,
                    	supplementaladdress : supplementaladdress,
                    	storeCode : storeCode
                    },
                    function(o) {
                        if (o.code == serviceCode.SUC_CODE) {
                        	var arrmp = o.message.split(',');
                        	
                            var $deliveryTimeTemp = arrmp.length > 2? 
                            		$(deliveryTimeTemp.format([arrmp[0], '', 'disabled'])):
                            			$(deliveryTimeTemp.format([arrmp[0], val, '']));
                            		
                            $this.closest('tr').after($deliveryTimeTemp).addClass('td_no_border');
                            var $openOnlinePay = $(openOnlinePay.format([arrmp[1]]));
                            if (parent.find('input[name=supportonlinepay]')){
                                parent.find('input[name=supportonlinepay]').remove();
                            }
                            $this.after($openOnlinePay);
                            delivery.val(arrmp[0]);
                        }else{
                        	if (o.code == '27'){
                        		base.yumAlert(property.storeStop);
                        	}else if(o.code == '25'){
                        		base.yumAlert(property.addressNotInDeliveryHelp);
                        	}else if(o.code == '1'){
                        		base.yumAlert(property.storeClosed);
                        	} else if (o.code == serviceCode.STORE_CLOSED) {
                        		base.yumAlert(o.message);
                        	}else{
                        		base.yumAlert(o.message);//显示表store中ShutReason的值
                        	}
                        	
                        	delivery.val('');
                        	$this[0].checked = false;
                        }
                    }
                );
        }
    };
    
    var TimeUtil = function(args){
    	var span = '<span class="bc"/>';
    	var div = '<div/>';
    	var ul = '<ul/>';
    	var li = '<li/>';
    	var input = '<input type="hidden"/>';
    	
    	var currentTime = args.currentTime;
    	var isSecondDay = args.isSecondDay;
    	var listHH = [];
    	
    	var timeList = (function(){
    		var times = args.timeList;
    		var result = {};
    		for(var i in times){
    			var HH = times[i].hour;
    			var listMM = times[i].minutes;
    			listHH.push(HH);
    			result[HH] = listMM;
    		}
    		return result;
    	})();
    	
    	
    	var getMM = function(HH){
    		var listMM = timeList[HH];
    		var outDiv = $(div).addClass('macstyle');
    		var innerDiv = $(div).addClass('tag_select').text(listMM[0]);
    		var _ul = $(ul).addClass('tag_options');
    		var _input = $(input).attr('name', 'minute').val(listMM[0]);
    		
    		for(var i in listMM){
    			var _li = $(li)
    			.hover(function(){
    				$(this).addClass('hover');
    			},function(){
    				$(this).removeClass('hover');
    			})
    			.click(function(){
    				innerDiv.text($(this).text());
    				_input.val($(this).text());
    				_ul.hide();
    			});
    			_ul.append(_li.text(listMM[i]));
    		}
    		innerDiv.click(function(){_ul.show();});
    		return outDiv.append(innerDiv, _ul, _input);
    	};
    	
    	var getHH = function(){
    		var outDiv = $(div).addClass('macstyle');
    		var innerDiv = $(div).addClass('tag_select').text(listHH[0]);
    		var _ul = $(ul).addClass('tag_options');
    		var _input = $(input).attr('name', 'hour').val(listHH[0]);
    		
    		var HHclick = function(){
        		$(this).closest('.macstyle').siblings('.macstyle').after(getMM($(this).text())).remove();
        		innerDiv.text($(this).text());
        		_input.val($(this).text());
				_ul.hide();
        	};
        	
    		for(var i in listHH){
    			var _li = $(li)
    			.hover(function(){
    				$(this).addClass('hover');
    			},function(){
    				$(this).removeClass('hover');
    			})
    			.click(HHclick);
    			_ul.append(_li.text(listHH[i]));
    		}
    		innerDiv.click(function(){_ul.show();});
    		return outDiv.append(innerDiv, _ul, _input);
    	};
    	
    	this.getHtml = function(){
    		var date=new Date();
    		currentTimeEn=date.getFullYear()+"/"+(date.getMonth()+1)+"/"+date.getDate();
    		currentTimeCn=date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日";
    		var $span1 = $(span).text($.localStr({cn:currentTimeCn,en:currentTimeEn}, 1));
    		var $span2 = $(span).text(property.hour);
    		var $span3 = $(span).text(property.min);
    		var $input = $(input).attr('name', 'isSecondDay').val(isSecondDay);
    		
    		return $('<div/>').append($span1, getHH(), $span2, getMM(listHH[0]), $span3, $input);
    	};
    	
    };
    
    //-- 选择送餐时间（及时单、预约单）
    $('input[name=sendfoodtime]').live('click', function(){
    	var $this = $(this);
    	var selectTimeEl = $('.selectTime');
        var tip = $(this).attr('tip');
        //-- 及时单
        if(tip && tip == 'inTime'){
        	
        	selectTimeEl.empty().hide();
        }
        //-- 预约单
        else{
        	var addressId = this.value;
        	var data = {addressId : addressId};
        	if(me.isNewUser){
        		var values = addressId.split('-');
        		
        		if(!values[0] || !values[1] || !values[2]){
        			throw new Error( '"/getTimeByStore.action" parameters is null' );
        		}
        		data = {
        				cityCode : values[0],
        				mainAddressId : values[1],
        				supplementaladdress : values[2]
        				}
        	}
        	KFC_POST(
        			'/getTimeByStore.action',
        			data,
        			function(o){
        				if(o.timeList && o.timeList.length > 0){
        					var timeUtil = new TimeUtil(o);
        					selectTimeEl.empty().append(timeUtil.getHtml()).show();
        				}else if(o && o.code == serviceCode.OUT_OF_DELIVERY_TIME){
        					base.yumAlert(o.message);
        					$this.closest('td').find('[name=sendfoodtime]:first').click();
        				}else if(o && o.code == serviceCode.ADDR_NOT_FIND){
        					base.yumAlert(property.notFindAddress);
        					$this.closest('td').find('[name=sendfoodtime]:first').click();
        				}else{
        					base.yumAlert(property.serviceUnknown);
        					$this.closest('td').find('[name=sendfoodtime]:first').click();
        				}
        			}
    			);
        }
    });
    
    //-- 发送手机验证
    var sendSMSCode = function(){
    	var flag = true;
    	$.ajax({
    		url : requestContextPath + '/delOsAddrAction.action',
    		async : false,
    		data : {},
    		dataType : 'json',
    		type : 'post',
    		success : function(o){
    			if(o.code == serviceCode.FAIL_CODE){
        			flag = false;
        		}
    		}
    	});
    	return flag;
    };
    
    //-- 删除地址
    var del = function(){
    	var $this = $(this);
    	var needMailFlag = Boolean($this.attr('needMailFlag'));
    	var isOs = !!$this.attr('isos');
    	var removeEl = function(){
        	var tr = $this.parent().parent();
            if(tr.next()[0] && tr.next().attr('tip') == 'deliveryTime'){
            	tr.next().remove();
            }
            tr.remove();
        };
    	//-- 判断是否为OS同步地址
    	if(isOs){
    		var input = $('<input style="margin:0 5px" type="text"/>');
    		var btn = $('<button>'+pageMessage.base_confirm+'</button>');
    		var btn2 = $('<button style="margin-left:10px;">'+pageMessage.base_cancle+'</button>');
    		var div = $('<div style="text-align:left;margin:20px 0 15px;padding-left:20px;">'+property.validateCode+':</div>').append(input);
			div = $('<div/>').append(div, btn, btn2);
    		btn2.click(function(){div.remove();});
    		
    		btn.click(function(){
    			var code = input.val();
    			if($.trim(code) == ''){
    				base.yumAlert(property.codeNotNull);
    				return;
    			}
    			KFC_POST('/delOsAddress.action',{newCode : $.trim(code), oaddressid : $this.attr('isos')}, function(o){
    	    		if(o.code == serviceCode.SUC_CODE){
    	    			removeEl();
    	    			me.addressList.pop();
                		base.yumAlert(property.deleteSuccessfully);
    	    		}
    	    		else if(o.code == serviceCode.AUTH_CODE_UNCORRECT){
    	    			base.yumAlert(property.EorInputCode);
    	    		}else{
    	    			base.yumAlert(property.serviceUnknown);
    	    		}
    	    		div.dialog('close');
    	    	});
    		});
    		
    		
    		var loding = $('<div><p style="margin-top:20px;">'+property.msgSending+'...</p></div>').dialog({
    			title : pageMessage.customer_remind,
    			resizable: false,
    			modal : true,
    			closeOnEscape : true,
    			dialogClass : "ui-alert",
    			close: function () { $(this).remove(); },
    			position:{my: "center",
 				   at: "center",
 				   of: window,
 				   collision:"fit"}
    		});
    		
    		
    		if(sendSMSCode()){
    			setTimeout(function(){
    				loding.remove();
    				div.dialog({
            			title : pageMessage.customer_remind,
            			resizable: false,
            			modal : true,
            			closeOnEscape : true,
            			dialogClass : "ui-alert",
            			close: function () { $(this).remove(); },
            			position:{my: "center",
         				   at: "center",
         				   of: window,
         				   collision:"fit"}
            		});
    			}, 3000);
    		}else{
    			setTimeout(function(){
    				loding.remove();
    				base.yumAlert(property.sendFailed);
    			}, 3000);
    		}
    	}else{
    		base.yumConfirm(
        			property.deleteAddressWarn,
        			function(){
        		        var addressId = $this.parent().prev().children('input[name=selAddressId]').val();
        		        if(!me.isNewUser){
        		            if(addressId){
        		                KFC_POST(
        		                    '/delAddress.action',
        		                    {addressId : addressId, sendFlag : needMailFlag},
        		                    function(o){
        		                    	if(o.code == serviceCode.SUC_CODE){
        		                    		removeEl();
        		                    		me.addressList.pop();
        		                    		base.yumAlert(property.deleteSuccessfully);
        		                    	}else if(o.code  == serviceCode.DEL_ADDR_CODE){
        		                    		base.yumAlert(property.addressDel.format([me.userEmail]));
        		                    	}else{
        		                    		base.yumAlert(property.emailSendFail);
        		                    	}
        		                    }
        		                );
        		            }
        		        }else{
        		            removeEl();
        		            me.addressList.pop();
        		            base.yumAlert(property.deleteSuccessfully);
        		        }
        			}
        	);
    	}
    };
    

    this.isFinish = function(){
    	if(saveAddressBtn.is(':visible')){
    		saveAddressBtn.click();
    		return false;
    	}
    	//如果有一个地址，则被选中
		if(me.addressList.length == 1 && (!$('[name=selAddressId]:checked')[0])) {
			$('input[name=selAddressId]').each(function(){
				this.checked = true;
				$(this).click();
			});
			 return false;
		}
    	if(!$('[name=selAddressId]:checked')[0]){
    		base.yumAlert(property.addressNotSelect);
    		return false;
    	}
    	
        return true;
    };
    
    // -判断餐厅是否可以网上支付
    this.flagOpenOline = function(){
    	if($('[name=selAddressId]:checked')[0]){
    		return $('[name=selAddressId]:checked').next('input[name=supportonlinepay]').val();
    	}
    };
    
    
    //-- 新增地址
    addAddressBtn.click(add);
    //-- 地址多选按钮
    addressRadio.live('click', selectRadio).each(function(){
    	if($(this).is(':checked')){
    		$(this).click();
    	}
    });
    //-- 删除地址
    deleteBtn.live('click', del);
    //-- 保存地址
    saveAddressBtn.click(save);
    
};
// --------------------------------  地址  end  ------------------------------------------------ //



// --------------------------------  密码  begin  ------------------------------------------------ //

var KFC_Password = function(me){
	var _this = this;
	var editPwdDiv = $('#edit_pwd');
	var setPwdDiv = editPwdDiv.prev();
	var finishedDiv = editPwdDiv.next();
	
	//-- 修改密码
	var modifyPwdBtn = $('#modifyPwdBtn');
	//-- 解除密码
	var unlockPwdBtn = $('#unlockPwdBtn');
	//-- 设置密码
    var setPwdBtn = $('#setPassword');
    //-- 保存密码
    var savePwdBtn = $('#savePwd');
    //-- 取消
    var cancelBtn = savePwdBtn.next();
    
    var inputPassword = $('input[name=password]');
    var inputPassword1 = $('input[name=password1]');
    var inputPassword2 = $('input[name=password2]');
    var inputCode = $('input[name=code]');
    var img = inputCode.next('img');
    
    var passwordTest = /^[a-zA-Z0-9]{6,16}$/;
    
    this.empty = function(){
    	inputPassword1.val('');
    	inputPassword2.val('');
    	inputCode.val('');
    };

    var tab = function(e) {
        e.blur(function() {
            if (this.value == '') {
                $(this).addClass('dn').prev().removeClass('dn');
            }
        }).prev().focus(function() {
            $(this).addClass('dn').next().removeClass('dn').focus();
            $(this).addClass('dn').prev().removeClass('dn');
        });
    };
    //-- 初始化提示语
    tab(inputPassword1);
    tab(inputPassword2);
    inputPassword1.prev().val(property.inputPassword);
    inputPassword2.prev().val(property.inputPasswordAgain);
    inputCode.tip(property.inputCode);

    var refreshCode = function() {
    	// 过滤国际化的‘/en’标示
    	var pathTemp = requestContextPath;
    	
    	if(pathTemp.indexOf('/en')>0){
    		pathTemp=pathTemp.replace(/\/en/, '/');
		}
        setTimeout(function(){
        	img.attr('src', pathTemp + '/code.jsp?random=' + new Date().getTime());
        	}, 5);
    };

    //-- 刷新验证码
    inputCode.siblings('a,img').click(refreshCode);
 
    //-- 取消设置
    cancelBtn.click(function(){
    	if(_this.flag == 'SET'){
    		setPwdDiv.show();
			editPwdDiv.hide();
			inputPassword1.val('');
    	}
    	else if(_this.flag == 'MODIFY'){
    		finishedDiv.show();
    		editPwdDiv.hide();
    	}
    });
    
    //-- 修改密码
    modifyPwdBtn.click(function(){
    	_this.flag = 'MODIFY';
		reSet();
    	finishedDiv.hide();
    	editPwdDiv.show();
    	refreshCode();
    });
    
    //-- 解除密码
    unlockPwdBtn.click(function(){
    	var rush = function(){var _this = $(this);setTimeout(function(){_this.attr('src', requestContextPath + '/code.jsp?random=' + new Date().getTime());}, 5);},
    	element_p = $('<p class="mt6px"/>'),
    	element_p1 = $('<p style="margin: 5px 0 0;"/>'),
    	element_a1 = $('<a href="javascript:;" class="fl_l"><img style="vertical-align:middle;margin-right:10px;" src="res/images/edit_ok_btn.jpg"></a>'),
    	element_a2 = $('<a href="javascript:;" style="line-height:20px;">'+property.cancelLift+'</a>'),
    	element_input = $('<input type="text" class="input_1"/>'),
    	element_img = $('<img style="vertical-align:middle;margin-right:10px;"/>').click(rush),
    	element_code = $('<a href="javascript:;">'+property.plsRefresh+'</a>').click(function(){element_img.click();});
	    element_p.append(element_input, element_img, element_code);
	    element_p1.append(element_a1, element_a2);
	    element_input.tip(property.inputCode);
	    var unlockDiv = $('<div/>').append(element_p, element_p1);
	    element_a2.click(function(){
	    	unlockDiv.remove();
	    	finishedDiv.show();
	    });
	    element_a1.click(function(){
	    	if(element_input.val() != '' && element_input.val() != property.inputCode){
	    		/** 非法字符校验*/
	            if (common.isStr2(element_input.val(), 1)) {
	            	base.yumAlert(property.invaildStringError);
	                return;
	            }
	    		
	    		if(me.isNewUser){
		    		if(validateCode(element_input.val()))
		    		unlockDiv.remove();
					setPwdDiv.show();
					inputPassword.val('');
					reSet();
					return;
		    	}
	    		KFC_POST(
	    				'/unlockPassword.action',
	                    { auth : element_input.val() },
	                    function(o) {
	                        if (o.code == serviceCode.SUC_CODE) {
	                        	base.yumAlertBack(
	                        			property.unlockPasswordSuccessfully,
	                        			function(){
	                        					unlockDiv.remove();
	                        					setPwdDiv.show();
	                        					// 解除密码，刷新页面
	                        					window.location.href = requestContextPath+"/customer.action";
	                        				}
	                        			);
	                        } else if (o.code == serviceCode.AUTH_CODE_UNCORRECT) {
	                            base.yumAlertBack(property.EorInputCode, function(){
	                            	element_input.val('').focus();
	                            	element_img.click();
	                            });
	                        } else {
	                            base.yumAlert(property.serviceUnknown);
	                        }
	                    });
	    	}else{
	    		base.yumAlert(property.inputCode);
	    	}
	    });
    	finishedDiv.after(unlockDiv);
    	finishedDiv.hide();
    	setTimeout(function(){element_img.attr('src', requestContextPath + '/code.jsp?random=' + new Date().getTime());}, 5);
    	
    });
    
    
    //-- 设置密码
    setPwdBtn.click(function(){
    	//-- 新用户
    	if(me.isNewUser){
    		reSet();
    		_this.flag = 'SET';
    		setPwdDiv.hide();
    		editPwdDiv.show();
    		refreshCode();
    	}
    	//-- 老用户发送邮件
    	else{
            KFC_POST('/setPassword.action',{},
              function(o){
            	  if(o.code == serviceCode.SUC_CODE){
            		  base.yumAlert(property.resetMail.format([me.userEmail]) ); 
            	  }else if(o.code == serviceCode.MAIL_SEND_FAIL){
            		  base.yumAlert(property.emailSendFail);
            	  }else if(o.code == serviceCode.USER_NOT_LOGIN){
            		  location.href = requestContextPath + '/login.action';
            	  }else{
            		  base.yumAlert(property.serviceUnknown);
            	  }
              }
          );
    	}
    });
    
    //-- 保存密码
    savePwdBtn.click(function() {
        var passwordVal = inputPassword1.val();
        var password2Val = inputPassword2.val();
        var inputCodeVal = $.trim(inputCode.val());
        
        if(passwordVal == '' || !/^[a-zA-Z0-9]{6,16}$/.test(passwordVal)){
        	base.yumAlert(property.EorPasswordFormat);
        	return;
        }

        if (passwordVal !== password2Val) {
            base.yumAlert(property.twoPasswordsDoNotMatch);
            return;
        }
        if (!passwordTest.test(passwordVal)) {
            base.yumAlert(property.EorPasswordFormat);
            return;
        }
        if (common.isStr2(passwordVal, 1)) {
        	base.yumAlert(property.invaildStringError);
            return;
        }
        
        if (inputCodeVal == '' || inputCodeVal == property.inputCode) {
            base.yumAlert(property.inputCode);
            refreshCode();
            return;
        }
        
        /** 非法字符校验*/
        if (common.isStr2(inputCodeVal, 1)) {
        	base.yumAlert(property.invaildStringError);
            return;
        }
        
        if (!me.isNewUser) {
            KFC_POST(
                '/modifyPassword.action',
                { password : passwordVal, auth : inputCodeVal },
                function(o) {
                    if (o.code == serviceCode.SUC_CODE) {
                    	base.yumAlertBack(
                    			property.setPasswordSuccessfully,
                    			function(){
                    					cancelBtn.click();
                    				}
                    			);
                    } else if (o.code == serviceCode.AUTH_CODE_UNCORRECT) {
                        base.yumAlertBack(property.EorInputCode, function(){
                        	inputCode.val('').focus();
                        	refreshCode();
                        });
                    } else if(o.code == serviceCode.USER_NOT_LOGIN){
                    	loginExit(function(){
                    		location.href = requestContextPath + '/login.action';
                    	});
                    }else {
                        base.yumAlert(property.serviceUnknown);
                    }
                }
            );
        } else {
        	//-- 校验验证码
        	if(inputCode.val() != ''){
        		if(validateCode(inputCode.val())){
	    			editPwdDiv.hide();
	    			finishedDiv.show();
	    			inputPassword.val(passwordVal);
	    			base.yumAlert(property.setPasswordSuccessfully);
        		}
        	}else{
        		base.yumAlert(property.inputCode);
        	}
        }
    });

    //-- 重置输入框
    var reSet = function(){
    	inputPassword1.val('').blur();
    	inputPassword2.val('').blur();
    	inputCode.val('').blur();
    };
    
    //-- 校验验证码
    var validateCode = function(auth){
    	var flag = false;
    	$.ajax({
    		url : requestContextPath + '/auth.action',
    		type : 'post',
    		data : {auth : auth},
    		dataType : 'json',
    		async : false,
    		success : function(o){
    			if(o.code == serviceCode.AUTH_CODE_UNCORRECT){
					base.yumAlertBack(
							property.EorInputCode,
							function(){
								inputCode.val('').focus();
								refreshCode();
							});
					
				}else if(o.code == serviceCode.SUC_CODE){
					flag = true;
				}else{
					base.yumAlert(property.serviceUnknown);
				}
    		}
    	});
    	return flag;
    };
    
    this.noPassworddFlag = false;
    this.isFinish = function(_me){
    	if(!me.isNewUser) return true;
    	if(inputPassword.val()) return true;
    	// 新用户注册时，未设置密码，则需要提示一次
    	var selAddress = $('[name=selAddressId]:checked');
    	if( !this.noPassworddFlag && !inputPassword1.val() && selAddress[0]){
    		selAddress = selAddress.parent().prev('td').text();
    		$('<div><span>' + property.noCodeWarn + selAddress.replace(/^(.).+(.{2})$/,'$1*……*$2')+pageMessage.period+ '</span></div>').dialog({
    			resizable: false,
    			minHeight:'96px',
    			modal: true,
    			closeOnEscape:true,
    			dialogClass:"ui-alert",
    			title:pageMessage.customer_remind,
    			position:{my: "center",
    				   at: "center",
    				   of: window,
    				   collision:"fit"},
    			buttons: {
    				customer_setCode: function() {
    					$(this).remove();
    					setPwdBtn.click();
    				},
    				customer_continueOrder: function() {
    					$(this).remove();
    					_me.click();
    				}
    			}
    		});
    		this.noPassworddFlag = true;
    		return false;
    	}
    	//return true;
    	return this.noPassworddFlag;
    };

    refreshCode();
};
// --------------------------------  密码  end  ------------------------------------------------ //


var KFC_Customer = function(){
	var me = this;
    this.isNewUser = $('#userFlag').val() == 0? true : false;  //  true : 新用户  , false : 已注册用户
    this.userEmail = $('#userEmail').val();
    this.userName = '';
    this.gender = '';
    this.phoneList = [];
    this.addressList = [];
    this.password = '';

    var KFC_base = new KFC_Base(this);
    var KFC_phone = new KFC_Phone(this);
    var KFC_address = new KFC_Address(this);
    var KFC_password = new KFC_Password(this);
   

    
    //-- 进入菜单
    $('#nextStep').click(function(){
    	 
    	 
        if(!KFC_base.isFinish()){
            return;
        }
        if(!KFC_phone.isFinish()){
            return;
        }
        if(!KFC_address.isFinish()){
            return;
        }
        if(!KFC_password.isFinish($(this))){
        	if(!KFC_password.noPassworddFlag){
        		base.yumAlert(property.notSavePassword);
        	}
        	return;
        }
        	
        $.cookie(yumCfg.myNotNeed,null);
        
        KFC_password.empty();
      
        if (KFC_address.flagOpenOline() == 'true'){
        	if (me.isNewUser) {
	            base.setAction('regCustomer.action');
	        } else {
	            base.setAction('shopping.action');
	        }
           
        }else{
        	base.yumAlertBack(property.notOnlinePay,function(){
	 	        if (me.isNewUser) {
	 	            base.setAction('regCustomer.action');
	 	        } else {
	 	            base.setAction('shopping.action');
	 	        }
	         });
        }
   
    });
};

$(function(){
	KFC_Customer();
});